﻿using daonaite.api.extends;
using daonaite.core.Catche;
using daonaite.core.DrawingCore;
using daonaite.core.Encryption;
using daonaite.DAL.system;
using daonaite.Model.system.login;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
using System.Configuration;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Text.Json;

namespace daonaite.api.Controllers.system
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LoginController : BaseController
    {

        private readonly CreateCode createcode;
        private readonly Md5 md5;
        private readonly D_user usercz;
        private readonly IConfiguration configuration;
        private readonly ICacheHelp cache;

        private readonly IHubContext<myHub> hub;

        public LoginController(CreateCode createcode, Md5 md5, D_user usercz, IConfiguration configuration, ICacheHelp cache, IHubContext<myHub> hub)
        {
            this.createcode = createcode;
            this.md5 = md5;
            this.usercz = usercz;
            this.configuration = configuration;
            this.cache = cache;
            this.hub = hub;
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult getImage()
        {
            string image;
            int value;
            string uuid = Guid.NewGuid().ToString("N");
            try
            {
                (image, value) = createcode.getcode();
                cache.set(uuid, value.ToString(), 60, 0);
                return Success(image, uuid);
            }
            catch (Exception e)
            {
                return Error(e.Message);
            }
           
            return Success();
        }

        [HttpPost]
        public async Task<IActionResult> denglu([FromBody] Dto_login data)
        {
            string yzm = cache.get<string>(data.code);
            if (data.yanzhengma != yzm)
            {
                return Error("验证码不正确");
            }
            cache.remove(data.code);

            var userinfo = await usercz.getUserByUsernameAsync(data.username);
            if(userinfo == null)
            {
                return Error("用户名不存在");
            }

            string md5pwd = md5.MD5Encrypt64(data.password);
            if(md5pwd!=userinfo.password)
            {
                return Error("密码错误");
            }

            // 用户登陆成功, 创建token
            Loginuser lguser = new Loginuser();
            userinfo.password = null;
            lguser.user = userinfo;
            var conf = configuration.GetSection("jwt");

            var claim = new Claim[]
            {
                new Claim("Issuer",conf["Issuer"]),
                new Claim("Audience",conf["Audience"]),
                new Claim("userid",JsonSerializer.Serialize(lguser))
            };

            var symmetricKeyAsBase64 = conf["SigningKey"];

            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(symmetricKeyAsBase64));

            SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            JwtSecurityToken token = new JwtSecurityToken(
             issuer: conf["Issuer"],
             audience: conf["Audience"],
             claims: claim,
             expires: DateTime.Now.AddHours(5),//5小时有效期
             signingCredentials: creds);

            string returnToken = new JwtSecurityTokenHandler().WriteToken(token);

            return Success("登录成功",returnToken);
        }
    }
}
